package com.lbssoft.gpsbd.dao;

import java.util.List;

import org.apache.ibatis.annotations.*;

import com.lbssoft.gpsbd.model.Position;
import com.lbssoft.gpsbd.model.vo.PositionStatus;

@Mapper
public interface PositionMapper {
	/**
	 * 获取系统所有设备最后的位置
	 * @param 
	 */

	@Select("SELECT a.id, a.deviceId, a.fixTime, a.longitude, a.latitude, a.attributes FROM lbs_positions a WHERE a.id IN ( SELECT positionId FROM lbs_devices )")
	List<Position> getLastPositions();
	
	/**
	 * 写入位置
	 * @param position
	 */
	@Insert("INSERT INTO lbs_positions(deviceid,fixTime,latitude,longitude,speed,course,accuracy,mode,attributes) VALUE(#{deviceId},#{fixTime},#{latitude},#{longitude},#{speed},#{course},#{accuracy},#{mode},#{attributes})")
	@Options(useGeneratedKeys=true, keyProperty="id")
	void addPosition(Position position);

	/**
	 * 获取用户下所有设备的最后位置
	 * @param uid
	 * @return
	 */
	@Select("SELECT t.deviceId,t.fixtime as time,t.latitude,t.longitude,t.speed,t.course,t.accuracy,t.`mode`,a.`status`,t.attributes FROM lbs_positions t LEFT JOIN lbs_devices a ON t.id = a.positionid LEFT JOIN lbs_user_device b ON a.id = b.deviceid where a.`status` is not null AND  a.`status` <>-1 AND b.userid = #{uid}")
	List<PositionStatus> getLastPostionByUid(@Param("uid") long uid);
	
	/**
	 * 根据设备和时间段查历史轨迹
	 * @param start
	 * @param end
	 * @param did
	 * @return
	 */
	@Select("SELECT id,deviceId,fixTime as time,latitude,longitude,speed,course,mode,attributes FROM lbs_positions where deviceid = #{did} AND fixTime BETWEEN #{start} AND #{end} ORDER BY  fixTime")
	List<Position> getHistory(@Param("start") String start,@Param("end") String end,@Param("did") long did);

//	/**
//	 * 根据用户id获取设备最后位置
//	 * @param userId
//	 * @return
//     */
//	@Select("SELECT t.deviceId, t.latitude, t.longitude, cast(t.speed AS SIGNED INTEGER) AS speed, cast(t.course AS SIGNED INTEGER) AS course, t.accuracy, t.fixTime AS time, t.mode, t.attributes FROM lbs_positions t INNER JOIN lbs_devices a ON t.id = a.positionid INNER JOIN lbs_user_device b ON b.deviceId = a.id WHERE b.userId = #{userId}")
//	List<Position> getLastPositionsByUserId(@Param("userId") long userId);

	/**
	 * 重置当日里程
	 * @param deviceId
	 * @param attributes
     */
	@Update("update lbs_positions t set attributes = #{attributes},servertime = t.servertime where id = (SELECT positionid from lbs_devices WHERE id = #{deviceId})")
	void resetTodayTrip(@Param("deviceId") long deviceId,@Param("attributes") String attributes);

	/**
	 * 根据设备id获取最后位置
	 * @param deviceId
	 * @return
     */
	@Select("SELECT * FROM lbs_positions where id =(SELECT positionid from lbs_devices where id = #{deviceId})")
	Position getPositionByDeviceId(@Param("deviceId") long deviceId);
}
